﻿using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using AgnisDAL;

namespace TestApplication
{
    /// <summary>
    /// Class used for automation settings; 
    /// Updates should be necessary only inside the app.config project files .
    /// </summary>
    public partial class SettingsForm : Form
    {     
        protected String ebmtDbConnectionString;
        protected String mappingInfoConnectionString;
        protected String agnisStagingConnectionString;
        SqlConnection myTestConnection;
        private FormContainer myFormContainer;
        AgnisDAL.AGNIS_FORMSDataSet dsAgnisForms = new AGNIS_FORMSDataSet();

        public void SetFormContainer(FormContainer myFContainer)
        {
            myFormContainer = myFContainer;
        }
        public SettingsForm()
        {
            InitializeComponent();
            //LoadConfigurationSettings();
        }
        private void SettingsForm_Load(object sender, EventArgs e)
        {
            LoadConfigurationSettings();
        }

        /// <summary>
        /// Load connexion settings from App.config file.
        /// </summary>
        public void LoadConfigurationSettings()
        {
            System.Configuration.Configuration config =
                        ConfigurationManager.OpenExeConfiguration(
                        ConfigurationUserLevel.None);

            System.Configuration.KeyValueConfigurationElement myEbmtDbKey =
                config.AppSettings.Settings["userDefinedEBMTDbConnectionString"];
            System.Configuration.KeyValueConfigurationElement myMappingInfoKey =
                config.AppSettings.Settings["userDefinedMappingInfoConnectionString"];
            System.Configuration.KeyValueConfigurationElement myAgnisStagingKey =
               config.AppSettings.Settings["userDefinedAgnisStagingConnectionString"];
            if (myEbmtDbKey.Value != "" && myMappingInfoKey.Value != "" & myAgnisStagingKey.Value != "")
            {
                ReadUserDefinedConnectionStrings(myEbmtDbKey, myMappingInfoKey, myAgnisStagingKey);
            }
            else
            {
                ReadDefaultConnectionStrings();
            }
            buttonBehavior(myEbmtDbKey.Value.ToString(), myMappingInfoKey.Value.ToString(), myAgnisStagingKey.Value.ToString());
        }
        private void Get_EbmtCustomdb_ConfigurationSettings(string keyName)
        {
            System.Configuration.Configuration config =
                        ConfigurationManager.OpenExeConfiguration(
                        ConfigurationUserLevel.None);
       
            System.Configuration.KeyValueConfigurationElement myEbmtDbKey =
                config.AppSettings.Settings[keyName];

            if (myEbmtDbKey.Value != "")
            {
                ebmtDbConnectionString = myEbmtDbKey.Value;
            }
            else
            {
                ReadDefaultConnectionStrings();
            }
        }

        private void Get_AgnisCustomdb_ConfigurationSettings(string keyName)
        {
            System.Configuration.Configuration config =
                        ConfigurationManager.OpenExeConfiguration(
                        ConfigurationUserLevel.None);

            System.Configuration.KeyValueConfigurationElement myAgnisDbKey =
                config.AppSettings.Settings[keyName];

            if (myAgnisDbKey.Value != "")
            {
                agnisStagingConnectionString = myAgnisDbKey.Value;
            }
            else
            {
                ReadDefaultConnectionStrings();
            }
        }

        private void ReadDefaultConnectionStrings()
        {
            ConnectionStringSettingsCollection connections =
                ConfigurationManager.ConnectionStrings;

            if (connections.Count != 0)
            {
                // Get the collection elements.
                foreach (ConnectionStringSettings connection in
                 connections)
                {
                    string name = connection.Name;
                    if (connection.Name.IndexOf("EBMTDb") > -1)
                    {
                        ebmtDbConnectionString = connection.ConnectionString;
                        txtConnectionString.Text = ebmtDbConnectionString;                        
                    }
                    if (connection.Name.IndexOf("Mapping") > -1)
                    {
                        mappingInfoConnectionString = connection.ConnectionString;
                        txtConnectionString2.Text = mappingInfoConnectionString;
                    }
                    if (connection.Name.IndexOf("AGNIS_FORMS") > -1)
                    {
                        agnisStagingConnectionString = connection.ConnectionString;
                        txtConnectionString3.Text = agnisStagingConnectionString;
                    }
                }
                rdbEbmtDbState();
            }
        }
        private void rdbEbmtDbState()
        {
            if (ebmtDbConnectionString.IndexOf("145.88.211.27") > -1)
            {
                rdbLeiden.Checked = true;
            }
            else
            {
                rdbLocalDb.Checked = true;
            }
        }
        private void rdbAGNISDbState()
        {
            if (agnisStagingConnectionString.IndexOf("Test1") > -1)
            {
                rdbTest1.Checked = true;
            }
            else if (agnisStagingConnectionString.IndexOf("Test2") > -1)
            {
                rdbLocalDb.Checked = true;
            }
            else
            {
                rdbAgnisProd.Checked = true;
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            this.Validate();
            if (TestConnectionString(ebmtDbConnectionString)
                && TestConnectionString(mappingInfoConnectionString)
                && TestConnectionString(agnisStagingConnectionString))
            {
                SetUserDefinedConnectionStrings(ebmtDbConnectionString, mappingInfoConnectionString, agnisStagingConnectionString);                
                myFormContainer.OpenTestForm(ebmtDbConnectionString, mappingInfoConnectionString, agnisStagingConnectionString);
            }
            this.Close();
        }

        private bool TestConnectionString(String connString)
        {
            try
            {
                myTestConnection = new SqlConnection(connString);
                myTestConnection.Open();
                myTestConnection.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private void txtServerDBUSerAndPaswordName_Validating(object sender, CancelEventArgs e)
        {
            if (this.chkBoxSameUserId.Checked)
            {
                if (this.txtServerName.Text != "" &&
                this.txtEBMTDbName.Text != "" &&
                this.txtMappingInfoDbName.Text != "" &&
                this.txtUserName.Text != "" &&
                this.txtUserPassword.Text != "")
                {
                     ebmtDbConnectionString  = "packet size=4096;data source="+ this.txtServerName.Text+
                                               ";initial catalog=" + this.txtEBMTDbName.Text +
                                               ";persist security info=True" +
                                               ";user id=" + this.txtUserName.Text + 
                                                ";password=" + this.txtUserPassword.Text ;
                     txtConnectionString.Text = ebmtDbConnectionString;
                     mappingInfoConnectionString =  "packet size=4096;data source=" + this.txtServerName.Text +
                                                    ";initial catalog=" + this.txtMappingInfoDbName.Text +
                                                    ";persist security info=True" +
                                                    ";user id=" + this.txtUserName.Text +
                                                    ";password=" + this.txtUserPassword.Text;
                     txtConnectionString2.Text = mappingInfoConnectionString;
                     agnisStagingConnectionString  = "packet size=4096;data source=" + this.txtServerName.Text +
                                                     ";initial catalog=" + this.txtAgnisStagingName.Text +
                                                     ";persist security info=True" +
                                                     ";user id=" + this.txtUserName.Text +
                                                     ";password=" + this.txtUserPassword.Text;
                     txtConnectionString3.Text = agnisStagingConnectionString;
                }
            }
            else
            {
                if (this.txtServerName.Text != "" &&
                this.txtEBMTDbName.Text != "" &&
                this.txtMappingInfoDbName.Text != "" &&
                this.txtUserName.Text != "" &&
                this.txtUserName2.Text != "" &&
                this.txtUserPassword.Text != "" &&
                this.txtUserPassword2.Text != "")
                {
                    ebmtDbConnectionString = "packet size=4096;data source=" + this.txtServerName.Text +
                                              ";initial catalog=" + this.txtEBMTDbName.Text +
                                              ";persist security info=True" +
                                              ";user id=" + this.txtUserName.Text +
                                               ";password=" + this.txtUserPassword.Text;
                    txtConnectionString.Text = ebmtDbConnectionString;
                    mappingInfoConnectionString = "packet size=4096;data source=" + this.txtServerName.Text +
                                                   ";initial catalog=" + this.txtMappingInfoDbName.Text +
                                                   ";persist security info=True" +
                                                   ";user id=" + this.txtUserName2.Text +
                                                   ";password=" + this.txtUserPassword2.Text;
                    txtConnectionString2.Text = mappingInfoConnectionString;
                    agnisStagingConnectionString = "packet size=4096;data source=" + this.txtServerName.Text +
                                                    ";initial catalog=" + this.txtAgnisStagingName.Text +
                                                    ";persist security info=True" +
                                                    ";user id=" + this.txtUserName3.Text +
                                                    ";password=" + this.txtUserPassword3.Text;
                    txtConnectionString3.Text = agnisStagingConnectionString;
                }
            }
        }

      

        private void btnResetConnections_Click(object sender, EventArgs e)
        {
            this.txtServerName.Text = "";
            this.txtEBMTDbName.Text = "";
            this.txtMappingInfoDbName.Text = "";
            this.txtAgnisStagingName.Text = "";
            this.txtUserName.Text = "";
            this.txtUserName2.Text = "";
            this.txtUserName3.Text = "";
            this.txtUserPassword.Text = "";
            this.txtUserPassword2.Text = "";
            this.txtUserPassword3.Text = "";
            this.chkBoxSameUserId.Checked = false;
            LoadConfigurationSettings();
        }


        private void buttonBehavior(string ebmtConnection, string mappingConnection, string agnisConnection)
        {
            //Ebmt database radio button
            if(ebmtConnection.IndexOf("145.88.211.27") > -1)
            {
                rdbLeiden.Checked = true;
            }
            if (ebmtConnection.IndexOf("RICHARD") > -1)
            {
                rdbLocalDb.Checked = true;
            }
            //Agnis database radio button
            if (agnisConnection.IndexOf("RICHARD") > -1)
            {
                rdbTest1.Checked = true;
            }
        }

        private void ReadUserDefinedConnectionStrings(System.Configuration.KeyValueConfigurationElement ebmtDbKey,
            System.Configuration.KeyValueConfigurationElement mappingInfoKey, System.Configuration.KeyValueConfigurationElement agnisStagingKey)
        {
            ebmtDbConnectionString = ebmtDbKey.Value;
            txtConnectionString.Text = ebmtDbKey.Value;

            mappingInfoConnectionString = mappingInfoKey.Value ;
            txtConnectionString2.Text = mappingInfoKey.Value;

            agnisStagingConnectionString=  agnisStagingKey.Value;
            txtConnectionString3.Text = agnisStagingKey.Value;
        }       

        private void SetUserDefinedConnectionStrings(String ebmtDbConnectionString, 
                                                     String mappingInfoConnectionString,
                                                     String agnisStagingConnectionString)
        {
            System.Configuration.Configuration config =
                     ConfigurationManager.OpenExeConfiguration(
                     ConfigurationUserLevel.None);
                config.AppSettings.Settings["userDefinedEBMTDbConnectionString"].Value= ebmtDbConnectionString;
                config.AppSettings.Settings["userDefinedMappingInfoConnectionString"].Value = mappingInfoConnectionString;
                config.AppSettings.Settings["userDefinedAgnisStagingConnectionString"].Value = agnisStagingConnectionString;
            config.Save(ConfigurationSaveMode.Full);
        }      

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void chkBoxSameUserId_CheckedChanged(object sender, EventArgs e)
        {
            if (chkBoxSameUserId.Checked)
            {
                this.txtUserName2.Text = "";
                this.txtUserPassword2.Text="";
                this.txtUserName2.Enabled = false;
                this.txtUserPassword2.Enabled = false;
                this.txtUserName3.Text = "";
                this.txtUserPassword3.Text = "";
                this.txtUserName3.Enabled = false;
                this.txtUserPassword3.Enabled = false;
            }
            else
            {
                this.txtUserName2.Enabled = true;
                this.txtUserPassword2.Enabled = true;
                this.txtUserName3.Enabled = true;
                this.txtUserPassword3.Enabled = true;
            }
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            btnTestConnection.Enabled = false;
            if (TestConnectionString(ebmtDbConnectionString))
            { MessageBox.Show("Connection succeded."); }
            else
            { MessageBox.Show("Connection failed."); }
            btnTestConnection.Enabled = true;
        }

        private void btnTestConnection2_Click(object sender, EventArgs e)
        {
            btnTestConnection2.Enabled = false;
            if (TestConnectionString(mappingInfoConnectionString))
            { MessageBox.Show("Connection succeded."); }
            else
            { MessageBox.Show("Connection failed."); }
            btnTestConnection2.Enabled = true;
        }

        private void btnTestConnection3_Click(object sender, EventArgs e)
        {
            btnTestConnection3.Enabled = false;
            if (TestConnectionString(agnisStagingConnectionString))
            { MessageBox.Show("Connection succeded."); }
            else
            { MessageBox.Show("Connection failed."); }
            btnTestConnection3.Enabled = true;
        }

        
             

        private void SetConnectionStrings(String DbConnectionString, string Database)
        {
            switch(Database)
            {
                case "Ebmt": 
                    System.Configuration.Configuration config =
                     ConfigurationManager.OpenExeConfiguration(
                     ConfigurationUserLevel.None);
                    config.AppSettings.Settings["userDefinedEBMTDbConnectionString"].Value = DbConnectionString;
                    config.Save(ConfigurationSaveMode.Full);
                    txtConnectionString.Text = DbConnectionString;
                    //txtConnectionString3.Text = agnisStagingConnectionString;
                    break;
                case "Mapping":
                    System.Configuration.Configuration config2 =
                     ConfigurationManager.OpenExeConfiguration(
                     ConfigurationUserLevel.None);
                    config2.AppSettings.Settings["userDefinedMappingInfoConnectionString"].Value = DbConnectionString;
                    config2.Save(ConfigurationSaveMode.Full);
                    //txtConnectionString.Text = DbConnectionString;
                    txtConnectionString2.Text = DbConnectionString;                    
                    AgnisDAL.cAgnisDAL.SetConnectionString(DbConnectionString);
                    AgnisDAL.cAgnisDAL.LoadAgnisStagingDb(dsAgnisForms);
                    break;
                case "Agnis":
                    System.Configuration.Configuration config3 =
                     ConfigurationManager.OpenExeConfiguration(
                     ConfigurationUserLevel.None);
                    config3.AppSettings.Settings["userDefinedAgnisStagingConnectionString"].Value = DbConnectionString;
                    config3.Save(ConfigurationSaveMode.Full);
                    //txtConnectionString.Text = DbConnectionString;
                    txtConnectionString3.Text = DbConnectionString;
                    break;

                default: break;
            }           
            
        }
       
        

        private void rdbLeiden_CheckedChanged(object sender, EventArgs e)
        {
            

            if (rdbLeiden.Checked)
            {
                Get_EbmtCustomdb_ConfigurationSettings("userDefinedEBMTDbConnectionString_Leiden");
                if (!TestConnectionString(ebmtDbConnectionString))
                {
                    MessageBox.Show("User settings is not emplemented for Leiden Database.");
                }
                else
                {
                    SetConnectionStrings(ebmtDbConnectionString,"Ebmt");
                    txtConnectionString.Text = ebmtDbConnectionString.ToString();
                }
            }
            else
            {
                txtServerName.Text = "";
                txtEBMTDbName.Text = "";
                txtUserName.Text = "";
                txtUserPassword.Text = "";
            }
        }

        private void rdbLocalDb_CheckedChanged(object sender, EventArgs e)
        {
            
            if (rdbLocalDb.Checked)
            {
                Get_EbmtCustomdb_ConfigurationSettings("userDefinedEBMTDbConnectionString_Local");
                if (!TestConnectionString(ebmtDbConnectionString))
                {
                    MessageBox.Show("Connexion failed to your local EBMT Database!", "Something's wrong with Database");
                }
                else
                {
                    SetConnectionStrings(ebmtDbConnectionString,"Ebmt");
                    txtConnectionString.Text = ebmtDbConnectionString.ToString();
                }
            }
            else
            {
                txtServerName.Text = "";
                txtEBMTDbName.Text = "";
                txtUserName.Text = "";
                txtUserPassword.Text = "";
            }
        }

        private void rdbTest1_CheckedChanged(object sender, EventArgs e)
        {
            
            if (rdbTest1.Checked)
            {
                //MessageBox.Show("bouton 1");
                Get_AgnisCustomdb_ConfigurationSettings("userDefinedAgnisStagingConnectionString_Test1");
                if (!TestConnectionString(agnisStagingConnectionString))
                {
                    MessageBox.Show("Connexion failed to your local AGNIS_FORMS Database!", "Something's wrong with your settings!");

                }
                else
                {
                    SetConnectionStrings(agnisStagingConnectionString, "Agnis");
                }
                txtConnectionString3.Text = agnisStagingConnectionString.ToString();
            }
            else
            {
                txtServerName.Text = "";
                txtAgnisStagingName.Text = "";
                txtUserName3.Text = "";
                txtUserPassword3.Text = "";
            }
        }

        private void rdbTest2_CheckedChanged(object sender, EventArgs e)
        {            
            if (rdbTest2.Checked)
            {
                //MessageBox.Show("Bouton 2");
                Get_AgnisCustomdb_ConfigurationSettings("userDefinedAgnisStagingConnectionString_Test2");
                if (!TestConnectionString(agnisStagingConnectionString))
                {
                    MessageBox.Show("Connexion failed to your local AGNIS_FORMS_Test2 Database!", "Something's wrong with your settings!");

                }
                else
                {
                    SetConnectionStrings(agnisStagingConnectionString, "Agnis");
                }
                txtConnectionString3.Text = agnisStagingConnectionString.ToString(); ;
            }
            else
            {
                txtServerName.Text = "";
                txtAgnisStagingName.Text = "";
                txtUserName3.Text = "";
                txtUserPassword3.Text = "";
            }
        }

        
    }
}
